/**
 * 由 WangYu 创建
 * 日期 2017/9/26
 */
import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    TouchableOpacity, StatusBar, TextInput, TouchableNativeFeedback,NativeModules
} from 'react-native';
import CommonNavigationBar from "../../view/CommonNavigationBar";
import Toast from "teaset/components/Toast/Toast";
import Button from "../../view/Button";
import NetUtils from "../../util/NetUtils";
import Api from "../../util/Api";
import {themeColor} from "../../util/Config";
import StringUtil from "../../util/StringUtil";
import DeviceInfo from 'react-native-device-info';
import {Actions} from "react-native-router-flux";
import { login} from "../../redux/action";
import {connect} from "react-redux";
import Spinner from "../../view/Spinner";
 class RegisterPage extends Component {

    constructor(props) {
        super(props);
        this.state = {
            phone: '',
            warnText: '',
            passWord: '',
            imageUrl: 'a',
            picCode: '',
            msgCode: '',
            sendCodeStatusText: '发送校验码',
            isSending: false,
            seconds: 60,
            progressVisible:false
        }
    }

    render() {
        return (
            <View style={styles.container}>
                {/*状态栏*/}
                <StatusBar
                    backgroundColor={'#ffe466'}
                    barStyle="light-content"
                    animated={true}/>
                {/*标题栏*/}
                <CommonNavigationBar backgroundColor={'#ffe466'}
                                     title='用户注册'/>
                <View style={{
                    paddingLeft: 20,
                    paddingRight: 20,

                }}>
                    {/*账号和密码输入框*/}
                    <TextInput style={[styles.textInputStyle, {marginTop: 20}]}
                               underlineColorAndroid={'transparent'}
                               multiline={true}
                               placeholder={'请您输入手机号'}
                               placeholderTextColor={'#d5d5d5'}
                               keyboardType={'numeric'}
                               maxLength={11}
                               onChangeText={text => this.setState({phone: text})}/>

                    <View style={{
                        flexDirection: 'row',
                        marginTop: 15,
                        borderWidth: 0.5,
                        borderRadius: 3,
                        borderColor: '#aaaaaa'
                    }}>
                        <TextInput style={[styles.textInputStyle, {
                            flex: 1,
                            borderWidth: 0,
                            borderTopRightRadius: 0,
                            borderBottomRightRadius: 0
                        }]}
                                   underlineColorAndroid={'transparent'}
                                   multiline={true}
                                   placeholder={'验证码'}
                                   placeholderTextColor={'#d5d5d5'}
                                   maxLength={4}
                                   onChangeText={text => this.setState({picCode: text})}/>
                        <TouchableOpacity onPress={() => this.getImage()}>
                            <Image style={{width: 90, height: 30}} source={{uri: this.state.imageUrl}}
                                   resizeMode={'stretch'}/>
                        </TouchableOpacity>
                    </View>
                    <View style={{
                        flexDirection: 'row',
                        marginTop: 15,
                        borderWidth: 0.5,
                        borderRadius: 3,
                        borderColor: '#aaaaaa'
                    }}>
                        <TextInput style={[styles.textInputStyle, {
                            flex: 1,
                            borderWidth: 0,
                            borderTopRightRadius: 0,
                            borderBottomRightRadius: 0
                        }]}
                                   underlineColorAndroid={'transparent'}
                                   multiline={true}
                                   placeholder={'请输入校验码'}
                                   placeholderTextColor={'#d5d5d5'}
                                   keyboardType={'numeric'}
                                   maxLength={6}
                                   onChangeText={text => this.setState({msgCode: text})}/>
                        <TouchableNativeFeedback onPress={() =>!this.state.isSending&&this.sendMessageCode()}>
                            <Text style={[styles.textStyle,{backgroundColor:this.state.isSending?'#f0f0f0':themeColor,color:this.state.isSending?'#aaaaaa':'black'}]}>{this.state.sendCodeStatusText}</Text>
                        </TouchableNativeFeedback>
                    </View>
                    <TextInput style={[styles.textInputStyle, {marginTop: 15}]}
                               underlineColorAndroid={'transparent'}
                               multiline={true}
                               placeholder={'登录密码'}
                               placeholderTextColor={'#d5d5d5'}
                               secureTextEntry={true}
                               onChangeText={text => this.setState({passWord: text})}
                               onSubmitEditing={() => Toast.message('提交')}/>
                    <Text style={{color: 'white', marginTop: 15,}}>{this.state.warnText}</Text>
                    <Button title={'完成'} onPress={() => this.check()} style={{marginTop: 15}}/>
                </View>
                <Spinner cancelable={true} visible={this.state.progressVisible} textContent={"加载中..."} textStyle={{color: '#FFF'}} />
            </View>
        );
    }


    componentDidMount() {
        this.getImage();
    }

    /**
     * 获取图片验证码
     */
    getImage() {
        NetUtils.get(Api.getImage, null, (result) => {
            if (result.code === 1) {
                this.setState({
                    imageUrl: result.object.url
                });
                this.imageId = result.object.imageId;
            }
        });
    }

    /**
     * 发送短息验证码
     */
    sendMessageCode() {
        let picCode = this.state.picCode;
        let phone = this.state.phone;
        if (picCode.length < 4) {
            Toast.message('图片验证码错误');
            return;
        }
        if (!StringUtil.isPhoneNumber(phone)) {
            Toast.message('请输入正确的手机号');
            return;
        }
        let params = 'vcode=' + picCode + '&imageId=' + this.imageId + '&mobile=' + phone;
        this.setState({
            sendCodeStatusText: '发送中...',
            isSending: true,
        });
        NetUtils.post(Api.sendMobileCode, params, result => {
            if (result.code === 1) {
                Toast.message('发送成功');
                //开始倒计时
                this.setState({sendCodeStatusText:this.state.seconds+'秒'});
                this.timer = setInterval(() => {
                    this.setState({
                        seconds: --this.state.seconds,
                        sendCodeStatusText:this.state.seconds+'秒'
                    });
                    if(this.state.seconds <= 0){
                        this.timer && clearInterval(this.timer);
                        this.setState({
                            seconds:60,
                            sendCodeStatusText:'发送校验码',
                            isSending:false
                        });
                    }
                }, 1000);
            } else {
                Toast.message(result.message);
                this.setState({
                    sendCodeStatusText:'发送校验码',
                    isSending:false
                });
                //-2 图片验证码失效  重新获取
                result.code === -2 && this.getImage();
            }
        });
    }

    check() {
        let {phone, passWord, msgCode} = this.state;
        if (!StringUtil.isPhoneNumber(phone)) {
            this.setState({warnText: '请输入正确的手机号'});
            Toast.message('请输入正确的手机号');
            return;
        }
        if (msgCode === '') {
            this.setState({warnText: '短信验证码不能为空'});
            Toast.message('短信验证码不能为空');
            return;
        }
        if (msgCode.length < 6) {
            this.setState({warnText: '验证码为6位'});
            Toast.message('验证码为6位');
            return;
        }
        if (passWord.length < 6) {
            this.setState({warnText: '登录密码至少6位'});
            Toast.message('登录密码至少6位');
            return;
        }
        if (passWord.length > 16) {
            this.setState({warnText: '登录密码不可超出16位'});
            Toast.message('登录密码不可超出16位');
            return;
        }
        this.register();
    }

    /**
     * 注册
     */
    register(){
        this.setState({progressVisible:true});
        let {phone, passWord, msgCode} = this.state;
        let params='mobile='+phone+'&password=';
        NativeModules.MyNativeMoudle.privateEncrypt(passWord,(pwd)=>{
            params+=encodeURI(pwd)+'&pcode='+msgCode+'&iemi='+DeviceInfo.getUniqueID()+'&channel=1001';
            NetUtils.post(Api.register,params,result=>{
                if(result.code!==1){
                    Toast.message(result.message);
                    return;
                }
                Toast.success('登录成功', 'short', 'center');
                //netutil用的api存值
                Api.isLogin=true;
                Api.userInfo=result.object;
                //发起登录action
                this.props.dispatch(login(result.object));
                Actions.MainPage({type:'reset'});
                //本地存储userid和token
                storage.save({
                    key: 'userInfo',  // 注意:请不要在key中使用_下划线符号!
                    data: {
                        userId:result.object.userId,
                        token:result.object.token
                    },
                });
            },()=>this.setState({progressVisible:false}))
        })
    }

    componentWillUnmount() {
        this.timer && clearInterval(this.timer);
    }
}
export default connect()(RegisterPage);
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#ffe466',
    },
    textInputStyle: {
        height: 30,
        backgroundColor: 'white',
        borderRadius: 3,
        borderWidth: 0.5,
        borderColor: '#aaaaaa',
        padding: 0,
        paddingLeft: 10,
        color: '#010101'
    },
    textStyle: {
        color: 'black',
        width: 90,
        height: 30,
        backgroundColor: themeColor,
        textAlignVertical: 'center',
        textAlign: 'center',
    },


});
